import {CompareRemakeService} from "./service";
import style from "./style.css";

@Midway.MidwayModule({
    code: "CompareRemake",
    template: require('./view.html'),
    style: style,
    dependLibs: ['knockout', 'response-tip']
})
class CompareRemake extends CommonClass {

    constructor() {
        super();
        this.metaInfo.name = 'CompareRemake';
        this.metaInfo.type = ConstVariable.PresenterType.FUNCTIONAL;
        this.viewModel = {
            title: "",
            items: ko.observableArray([]),
            symbols: ["＜", "＞", "≤", "≥", "＝", "≈"]
            // hasCNChar: hasIncludeCNChar
        };
        this.correctAnswer = [];
        this.symbolMove = null;
        this.acceptArea = [];
        this.moveText = "";
        this.scrollObj = {left: 0, top: 0};
        this.mixDistanceX = 80;
        this.mixDistanceY = 50;
        this.mouseDown = false;
        this.clickOffset = {};
        //统计用
        this.itemIndexClass = 'module_number';
        this.dataType = 'data-item';
        this.statisticClass = "B";
        this.toggleSwitch = false;
        //状态恢复用
        this.showHintInfo = {'hasShow': false, 'result': undefined};
        this.showAnswerInfo = {'hasShow': false, 'type': undefined};
        //答题情况三种状态
        this.answerState = "NO_ANSWER";
        this.service = undefined;
    }

    update(view, model) {
        this._model = model;
        ko.cleanNode(this.$view[0]);
        this._initPresenter();
    }

    $launch() {
        var self = this;
        self.$view = $(this.View);
        for (var index = 0, len = this.Model.questionData.items.length; index < len; index++) {
            this.Model.questionData.items[index].symbol = this._mapData(this.Model.questionData.items[index].symbol);
        }
        self.$compareMain = self.$view.find('.compare_main');
        //初始化Presenter
        self._initPresenter();
        self._bindEvent();
    }

    $release() {
        this.$removeEventListener();
        ko.cleanNode(this.$view[0]);
        this._unbindEvent();
        this.viewModel = null;
    }

    getService() {
        if (this.service === undefined) {
            this.service = new CompareRemakeService(this);
        }
        return this.service;
    }

    _bindEvent() {
        //点击选中交互
        this.$view
            .on('click', '.mask', this._onOptionsSelected.bind(this));
        this.$view.find('.textentry')
            .on('click', this._onSymbolClick.bind(this))
            .on('mousedown', this._onSymbolFocus.bind(this))
            .on('mouseup', this._onSymbolBlur.bind(this))
    }

    _unbindEvent() {
        this.toggleSwitch = true;
        this.$view.off('click', '.mask');
        this.$view.find('.textentry').off();
    }

    _initPresenter() {
        var self = this;
        this.viewModel.title = this.Model.questionData.title;
        if (this.viewModel.title && this.viewModel.title.length > 38) {
            this.$view.find(".tit").addClass("s_tit");
        }
        var items = [];
        $.each(this.Model.questionData.items, function (key, value) {
            items.push({
                left: value.left,
                leftCss: hasIncludeCNChar(value.left) ? '' : 'fz_em_big',
                userAnswer: ko.observable(''),
                right: value.right,
                rightCss: hasIncludeCNChar(value.right) ? '' : 'fz_em_big'
            });
            self.correctAnswer.push({answer: self._mapData(value.symbol)});
        });
        this.viewModel.items(items);
        ko.applyBindings(self.viewModel, self.$view[0]);
    }

    _onOptionsSelected(e) {
        if (this.toggleSwitch) {
            return;
        }
        var target = e.target;
        var curr = target.parentNode;
        var prev = curr.parentNode.querySelector('.ui_btn_selected');
        prev && prev !== curr && prev.classList.remove('ui_btn_selected');
        if (curr.classList.contains('ui_btn_selected')) {
            this._onOptionsCancelSelected();
        } else {
            curr.classList.add('ui_btn_selected');
            this.moveText = curr.children[0].innerHTML;
        }
    }

    _onOptionsCancelSelected() {
        this.$view.find('.ui_btn_selected').removeClass('ui_btn_selected');
        this.moveText = '';
    }

    _onSymbolClick(e) {
        e.preventDefault();
        if (this.toggleSwitch) {
            return;
        }
        var target = e.target;
        var hasInput = !!this.moveText;
        //点击在textentry或子节点em上
        if (target.classList.contains('textentry')) {
            target = target.children[0];
        }
        target.innerHTML = this.moveText;

        this._onOptionsCancelSelected();
        this._checkAnswer();

        //通知保存状态
        if (hasInput) {
            //题目作答状态改变，按钮变为可提交
            this.dispatchEvent('questionStateChange', ConstVariable.PresenterEventType.IC_PLAYER_EVENT, {canSubmit: true});
        }
    }

    _onSymbolDblClick(e) {
        if (this.toggleSwitch) {
            return;
        }
        var text = this.moveText;
        this.moveText = '';
        this._onSymbolClick.call(this, e);
        this.moveText = text;
    }

    _onSymbolFocus(e) {
        if (this.toggleSwitch || !this.isPPTShell) {
            return;
        }
        var target = e.target;
        //.textentry或子节点em
        if (target.tagName.toUpperCase() === 'EM') {
            target = target.parentNode;
        }
        if (target.classList.contains('com_s_right')) {
            target.classList.remove('com_s_right') && target.classList.add('com_s_right_on');
        } else if (target.classList.contains('com_s_error')) {
            target.classList.remove('com_s_error') && target.classList.add('com_s_error_on')
        } else {
            target.classList.add('com_s_on');
        }
    }

    _onSymbolBlur(e) {
        if (this.toggleSwitch || !this.isPPTShell) {
            return;
        }
        var target = e.target;
        //.textentry或子节点em
        if (target.tagName.toUpperCase() === 'EM') {
            target = target.parentNode;
        }
        if (target.classList.contains('com_s_right_on')) {
            target.classList.remove('com_s_right_on') && target.classList.add('com_s_right');
        } else if (target.classList.contains('com_s_error_on')) {
            target.classList.remove('com_s_error_on') && target.classList.add('com_s_error')
        } else {
            target.classList.remove('com_s_on');
        }
    }

    _checkAnswer() {
        this._countAnswerPosition();
        var area = this.acceptArea;
        var modelItems = this.viewModel.items();
        // var hasAnswer = false;
        var hasComplete = true;
        area.forEach(function (item, index) {
            var content = item.textContent.trim();
            modelItems[index].userAnswer(content);
            // if(content && !hasAnswer){
            //     hasAnswer = true;
            // }
            if (!content && hasComplete) {
                hasComplete = false;
            }
        });
        this.answerState = hasComplete ? 'COMPLETE' : 'NO_COMPLETE';
    }

    _clearEffect() {
        this._onOptionsCancelSelected();
        this.$view.find('.com_s_on').removeClass('com_s_on');
        this.$view.find('.com_s_right_on').removeClass('com_s_right_on').add('com_s_right');
        this.$view.find('.com_s_error_on').removeClass('com_s_error_on').add('com_s_error');
    }

    _onSymbolMoveLeave2(event) {
        var self = event.data.self;
        if (this.toggleSwitch) {
            return;
        }
        if (self.acceptArea) {
            for (var i = 0, len = self.acceptArea.length; i < len; i++) {
                self.acceptArea[i].obj.removeClass("com_s_on");
                self.acceptArea[i].obj.removeClass("com_s_error_on");
                self.acceptArea[i].obj.removeClass("com_s_right_on");
            }
        }

        self.symbolMove.css({
            display: "none"
        });
    }

    _onSymbolMoveLeave(selector, e) {
        if (this.toggleSwitch) {
            return;
        }
        var self = this;
        self.mouseDown = false;
        var left = self.symbolMove.offset().left + self.scrollObj.left;
        var top = self.symbolMove.offset().top + self.scrollObj.top;

        for (var i = 0, len = self.acceptArea.length; i < len; i++) {
            if (left >= self.acceptArea[i].left && top >= self.acceptArea[i].top &&
                left <= self.acceptArea[i].left + self.acceptArea[i].width &&
                top <= self.acceptArea[i].top + self.acceptArea[i].height) {
                self.viewModel.items()[i].userAnswer(self.moveText);
                self.answerState = "NO_COMPLETE";
                //通知保存状态
                self.$dispatchEvent($PresenterEvent['InteractionStateRecoverFilter'].PRESENTER_STATE_CHANGE,
                    PresenterEventType.IC_PLAYER_EVENT);
                //题目作答状态改变，按钮变为可提交
                self.$dispatchEvent($PresenterEvent['AnswerFlowController'].QUESTION_STATE_CHANGE,
                    PresenterEventType.IC_PLAYER_EVENT, {canSubmit: true});
                break;
            }
        }
        for (var i = 0, len = self.acceptArea.length; i < len; i++) {
            self.acceptArea[i].obj.removeClass("com_s_on");
            self.acceptArea[i].obj.removeClass("com_s_error_on");
            self.acceptArea[i].obj.removeClass("com_s_right_on");
        }
        self.mouseDown = false;
        self.symbolMove.css({
            display: "none"
        });
    }

    _onSymbolStaticClick(selector, e) {
        if (this.toggleSwitch) {
            return;
        }
        var self = this;
        var $this = $(e.target);
        var index = $this.attr('index') ? $this.attr('index') : $this.children().attr('index');
        self._setScroll();
        self._countAnswerPosition();
        if (!self.viewModel.items()[index] || self.viewModel.items()[index].userAnswer() == '') {
            return;
        }
        self.viewModel.items()[index].userAnswer('');
        //通知保存状态
        self.$dispatchEvent($PresenterEvent['InteractionStateRecoverFilter'].PRESENTER_STATE_CHANGE,
            PresenterEventType.IC_PLAYER_EVENT);
    }

    _onMaskClick(selector, e) {
        e.preventDefault();
        if (this.toggleSwitch) {
            return;
        }
        var $mainOffset = this.$compareMain.offset();
        var self = this;
        var $this = $(e.target);
        var offset = $this.offset(), thisMove = $this.parent();
        self.moveText = thisMove.find('.symbol').text();
        self._setScroll();
        self._countAnswerPosition();

        self.mouseDown = true;
        self.symbolMove.find('em').text(self.moveText);
        self.symbolMove.css({
            left: (offset.left - $mainOffset.left) + 'px',
            top: (offset.top - $mainOffset.top) + 'px',
            display: "inline-block"
        });
    }

    _onMouseMove(selector, e) {
        if (this.toggleSwitch) {
            return;
        }
        var $mainOffset = this.$compareMain.offset();
        var self = this;
        if (self.mouseDown) {
            e.preventDefault();
            var left, top;
            var height = self.symbolMove.height() / 2;
            var width = self.symbolMove.width() / 2;
            if (e.type == "touchmove") {
                var point = e.changedTouches[0];
                left = point.clientX - $mainOffset.left - width;
                top = point.clientY - $mainOffset.top - height;
            } else {
                left = e.clientX - $mainOffset.left - width;
                top = e.clientY - $mainOffset.top - height;
            }
            self.symbolMove.css({
                'left': left + 'px',
                'top': top + 'px'
            });
            if (this.isPPTShell) {
                left = self.symbolMove.offset().left + self.scrollObj.left;
                top = self.symbolMove.offset().top + self.scrollObj.top;
                for (var i = 0, len = self.acceptArea.length; i < len; i++) {
                    self.acceptArea[i].obj.removeClass("com_s_on");
                    self.acceptArea[i].obj.removeClass("com_s_error_on");
                    self.acceptArea[i].obj.removeClass("com_s_right_on");
                }
                for (var i = 0, len = self.acceptArea.length; i < len; i++) {
                    if (left >= self.acceptArea[i].left && top >= self.acceptArea[i].top &&
                        left <= self.acceptArea[i].left + self.acceptArea[i].width &&
                        top <= self.acceptArea[i].top + self.acceptArea[i].height) {
                        if (self.acceptArea[i].obj.hasClass("com_s_right")) {
                            self.acceptArea[i].obj.addClass("com_s_right_on");
                        } else if (self.acceptArea[i].obj.hasClass("com_s_error")) {
                            self.acceptArea[i].obj.addClass("com_s_error_on");
                        } else {
                            self.acceptArea[i].obj.addClass("com_s_on");
                        }
                        break;
                    }
                }
            }
        }
    }

    _setScroll() {
        var $scrolls = this.$view.find('.exam_box');
        this.scrollObj = {
            top: $scrolls.scrollTop(),
            left: $scrolls.scrollLeft()
        };
    }

    _countAnswerPosition() {
        if (!this.acceptArea.length) {
            this.acceptArea = this.$view.find('.textentry').get();
        }
    }

    _showAnswerCheck() {
        this._countAnswerPosition();
        var area = this.acceptArea;
        var answer = this.correctAnswer;
        // var isTrue = true;
        // 作答区域反馈
        this._clearEffect();
        for (var i = 0, len = area.length; i < len; i++) {
            var item = area[i];
            if (item.textContent.trim() === answer[i].answer) {
                item.classList.remove('com_s_error');
                item.classList.add('com_s_right');
            } else {
                item.classList.remove('com_s_right');
                item.classList.add('com_s_error');
            }
        }
    }

    _resetAnswerCheck() {
        var self = this;
        this._countAnswerPosition();
        var area = this.acceptArea;
        // 作答区域反馈
        for (var i = 0, len = area.length; i < len; i++) {
            area[i].classList.remove('com_s_right');
            area[i].classList.remove('com_s_error');
            // area[i].obj.removeClass('com_s_right');
            // area[i].obj.removeClass('com_s_error');
        }
        this._clearEffect();
        $(self.$view).find('.compare_bottom_tool').removeClass('statistic-compare-footer');
        $(self.$view).find('.exam_box ._compare_node').removeClass('module-interaction-compare').removeAttr(self.dataType);
        $(self.$view).find('.' + self.itemIndexClass).remove();
    }

    _setStatisticsViewAttr() {
        var self = this;
        var i = 1;
        $(self.$view).find('.compare_bottom_tool').addClass('statistic-compare-footer');
        $.each($(self.$view).find('.exam_box ._compare_node').addClass('module-interaction-compare'), function (k, item) {
            var $item = $(item);
            $item.prepend(self._createItemIndexDom(i));
            $item.attr(self.dataType, i);
            i++;
        });
    }

    _createItemIndexDom(index) {
        var self = this;
        var $div = $('<span></span>');
        $div.addClass(self.itemIndexClass).text('' + index + '');
        return $div;
    }

    _bindStatisticsView() {
        var self = this;
        $(self.$view).on('click', ".module_number", function (event) {
            $(self.$view).find('.' + self.itemIndexClass).css("color", "");
            self._clickPresenterItem(event, this);
        });
    }

    _clickPresenterItem(event, context) {
        var self = this;
        var index = $(context).parent().attr(self.dataType);
        //通知统计
        self.$dispatchEvent("statistics_call",
            PresenterEventType.IC_PLAYER_EVENT, {
                service: "statistic",
                method: "clickItem",
                args: [index - 1, this.statisticClass]
            });
        $(context).css("color", "green");
    }

    _toggleInteraction(enabled) {
        if (enabled) {
            this.toggleSwitch = false;
        } else {
            this._unbindEvent();
            this._clearEffect();
        }
    }

    _mapData(map) {
        var symbol = '';
        switch (map) {
            case 'lt':
                symbol = '＜';
                break;
            case 'gt':
                symbol = '＞';
                break;
            case 'lteq':
                symbol = '≤';
                break;
            case 'gteq':
                symbol = '≥';
                break;
            case 'eq':
                symbol = '＝';
                break;
            case 'abeq':
                symbol = '≈';
                break;
            case '<':
                symbol = '＜';
                break;
            case '>':
                symbol = '＞';
                break;
            case '=':
                symbol = '＝';
                break;
            case '≦':
                symbol = '≤';
                break;
            case '≧':
                symbol = '≥';
                break;
            default :
                symbol = map;
                break;
        }
        return symbol;
    }
}

function hasIncludeCNChar(str) {
    return /[\u4E00-\u9FA5\uF900-\uFA2D]/.test(str);
}